package com.litelimit.core.service.listener;

import com.litelimit.core.service.exception.LuaLoadException;
import com.litelimit.core.service.log.LiteLimitLog;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.StringRedisTemplate;

/**
 * 对lua脚本的预加载和缓存清除
 */
@RequiredArgsConstructor
public class LuaListener {

    private final StringRedisTemplate stringRedisTemplate;

    @EventListener(ApplicationStartedEvent.class)
    public void handlePreloadScript(){
        // spring boot data redis 3.*后不需要手动缓存，第一次访问时框架会自动完成

//        try {
//            DefaultRedisScript<Boolean> script = luaScriptLoader.getScript();
//            byte[] scriptBytes = script
//                    .getScriptAsString()
//                    .getBytes(StandardCharsets.UTF_8);
//            String limitScriptSha = stringRedisTemplate.execute((RedisConnection connection) -> {
//                // 底层调用 Redis 的 SCRIPT LOAD 命令
//                return connection.scriptingCommands().scriptLoad(scriptBytes);
//            });
//            LiteLimitLog.log.debug("lua脚本预加载...");
//        } catch (Exception e) {
//            throw new LuaLoadException("预加载Lua脚本失败", e);
//        }
    }

    @EventListener(ContextClosedEvent.class)
    public void handleDeleteScript(){
        try {
            stringRedisTemplate.execute((RedisConnection connection) -> {
                connection.scriptingCommands().scriptFlush();
                return true;
            });
            LiteLimitLog.log.debug("lua脚本缓存清除...");
        } catch (Exception e) {
            throw new LuaLoadException("清除Lua脚本缓存失败", e);
        }
    }

}
